/*
 * FirstDivide.cpp
 *
 *  Created on: 13/02/2014
 *      Author: root
 */

#include "FirstBranch.h"
#include "DppmParams.h"
#include "SortedBuffer.h"
#include "Tuple.h"
#include <iostream>
#include <stdlib.h>

using namespace std;


extern DppmParams * dppm;
extern SortedBuffer * tuples;
extern int rank, size;

int FirstBranch(){


	int numAct = dppm->getNumActivities();
	int maxIndFB = 0;
	int numModes[numAct];
	int numTuples = 1;
	int * c = (int*)malloc(sizeof(int)*numAct);
	for(int i = 0; ( i < numAct )&&( numTuples >= size ) ; i++){

		numModes[i] = dppm->getActivityNumModes(i);
		maxIndFB++;
		c[i] = numTuples *= numModes[i];

	}

	c = (int*)realloc(c,sizeof(int)*maxIndFB); //si reduce el tamaño del array no cambia el puntero de lugar???

	int div = numTuples / size ;
	int mod = numTuples % size ;

	int indexTuple = 0;
	int myTuples = rank < mod ? div + 1 : div;

	indexTuple = rank < mod ? ((div + 1) * rank ) : ((div + 1) * mod   +  div * (rank - mod));


	int startTuple[numAct];
	int aux = indexTuple;
	memset(startTuple,0,sizeof(int)*numAct);

	for(int j = 0 ; j <= maxIndFB ; j++){

		startTuple[j] = aux / c[maxIndFB - j];
		aux = aux % c[maxIndFB - j];

	}

	Tuple * t = Tuple::MakeTupleFromModes(startTuple,numAct,maxIndFB);
	tuples->push(t);
	int carry = 0;

	for(int i = 1; i < myTuples; i++){

		carry = 1;
		for(int j = maxIndFB; (carry == 1 && j >= 0); j--){

			carry = ++startTuple[j] / numModes[j];
			startTuple[j] %= numModes[j];

		}

		t = Tuple::MakeTupleFromModes(startTuple,numAct,maxIndFB);
		tuples->push(t);

	}

	return 0;
}
